package com.globalblue.view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.globalblue.Configurations;
import com.globalblue.DeployManager;
import com.globalblue.WindowManager;

public class ImprovedMainWindow {

	private JFrame frame;
	private JPanel mainPanel;
	private JLabel lblNewLabel;
	private JTextField ticketId;
	private JLabel lblNewLabel_1;
	private JTextField buildUrl;
	private JLabel lblUsername;
	private JTextField username;
	private JLabel lblPassword;
	private JLabel lblNewLabel_2;
	private JButton btnOk;
	private JSplitPane fileListSplitPane;
	private JScrollPane rightScrollPane;
	private JScrollPane leftScrollPane;
	private JPanel leftPanel;
	private JPanel rightPanel;
	private WindowManager windowManager;
	private JPanel newPanel;
	private static Logger logger = Logger.getLogger(ImprovedMainWindow.class);
	private JPasswordField password;
	private JFileChooser chooser;
	JComboBox<String> websiteDirectory;

	/**
	 * Create the application.
	 */
	public ImprovedMainWindow() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		try {
			UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e1) {
			e1.printStackTrace();
		}
		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(
				"images\\automationIcon.jpg"));
		frame.setResizable(false);
		frame.setBounds(100, 100, 820, 575);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainPanel = new JPanel();
		mainPanel.setBounds(0, 0, 814, 547);
		mainPanel.setPreferredSize(new Dimension(300, 280));
		mainPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		frame.getContentPane().setLayout(null);
		frame.getContentPane().add(mainPanel);
		mainPanel.setLayout(null);

		lblNewLabel = new JLabel("Ticket ID");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblNewLabel.setLocation(117, 106);
		lblNewLabel.setSize(116, 14);
		mainPanel.add(lblNewLabel);

		ticketId = new JTextField();
		ticketId.setText(Configurations.getTicketId());
		ticketId.setFont(new Font("Tahoma", Font.PLAIN, 14));
		ticketId.setBounds(320, 107, 305, 20);
		mainPanel.add(ticketId);
		ticketId.setColumns(10);

		lblNewLabel_1 = new JLabel("Build URL");
		lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblNewLabel_1.setBounds(117, 135, 130, 14);
		mainPanel.add(lblNewLabel_1);

		buildUrl = new JTextField();
		buildUrl.setText(Configurations.getBuildUrl());
		// buildUrl.setText("https://dev.global-blue.com/build/view/GRIPS/job/GripsMxBackOffice/232/artifact/src/dist/GripsMxBackOffice_GlobalBlue.GripsMXBackOffice.Web_0_0_0_232.zip");
		buildUrl.setFont(new Font("Tahoma", Font.PLAIN, 14));
		buildUrl.setBounds(320, 138, 305, 20);
		mainPanel.add(buildUrl);
		buildUrl.setColumns(10);

		lblUsername = new JLabel("Username");
		lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblUsername.setBounds(117, 168, 116, 14);
		mainPanel.add(lblUsername);

		username = new JTextField();
		username.setText(Configurations.getUsername());
		// username.setText("uwijekoon");
		username.setFont(new Font("Tahoma", Font.PLAIN, 14));
		username.setBounds(320, 169, 305, 20);
		mainPanel.add(username);
		username.setColumns(10);

		lblPassword = new JLabel("Password");
		lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblPassword.setBounds(117, 199, 150, 14);
		mainPanel.add(lblPassword);

		lblNewLabel_2 = new JLabel("Website Directory");
		lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblNewLabel_2.setBounds(117, 224, 200, 40);
		mainPanel.add(lblNewLabel_2);

		btnOk = new JButton("OK");
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				windowManager.performAction(ticketId.getText(),
						websiteDirectory.getSelectedItem().toString(), buildUrl
								.getText(), username.getText(), new String(
								password.getPassword()));
			}
		});
		btnOk.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnOk.setBounds(320, 261, 89, 23);
		mainPanel.add(btnOk);

		password = new JPasswordField();
		password.setFont(new Font("Tahoma", Font.PLAIN, 14));
		password.setBounds(320, 198, 305, 20);
		mainPanel.add(password);

		JLabel lblEnterFollowigDetails = new JLabel("Enter Followig Details");
		lblEnterFollowigDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
		lblEnterFollowigDetails.setBounds(261, 30, 243, 40);
		mainPanel.add(lblEnterFollowigDetails);

		JButton btnSeletFolder = new JButton("Selet Directory");
		btnSeletFolder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				chooser = new JFileChooser();
				if (websiteDirectory.getSelectedItem() != null) {
					chooser.setCurrentDirectory(new java.io.File(
							websiteDirectory.getSelectedItem().toString()));
				} else {
					chooser.setCurrentDirectory(new java.io.File("."));
				}
				chooser.setDialogTitle("Select Directory");
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				chooser.setAcceptAllFileFilterUsed(false);
				if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
					websiteDirectory.addItem(chooser.getSelectedFile()
							.getAbsolutePath());
					websiteDirectory.setSelectedItem(chooser.getSelectedFile()
							.getAbsolutePath());
				} else {
					System.out.println("No Selection ");
				}
			}
		});
		btnSeletFolder.setBounds(638, 232, 116, 23);
		mainPanel.add(btnSeletFolder);

		websiteDirectory = new JComboBox<String>();
		websiteDirectory.setFont(new Font("Tahoma", Font.PLAIN, 14));
		websiteDirectory.setBounds(320, 233, 305, 23);
		websiteDirectory.setModel(new DefaultComboBoxModel<String>(
				Configurations.getWebsiteDirectoryList()));
		websiteDirectory.addItem("");
		websiteDirectory.setSelectedItem("");
		mainPanel.add(websiteDirectory);
	}

	public void showMainWindow(WindowManager windowManager) {
		this.windowManager = windowManager;
		frame.setVisible(true);
	}

	public JComboBox<String> getWebsiteDirectory() {
		return websiteDirectory;
	}

	public void setWebsiteDirectory(JComboBox<String> websiteDirectory) {
		this.websiteDirectory = websiteDirectory;
	}

	public void showFileListWindow(final List<String> fileList) {

		try {
			JPanel fileListPanel = new JPanel();

			JLabel lblSelectFilesAnd = new JLabel(
					"Select files and folders to be deployed");
			lblSelectFilesAnd.setFont(new Font("Tahoma", Font.BOLD, 14));
			lblSelectFilesAnd.setBounds(254, 43, 374, 28);
			fileListPanel.add(lblSelectFilesAnd);

			fileListSplitPane = new JSplitPane();
			fileListSplitPane.setBounds(22, 110, 782, 227);
			fileListSplitPane.setDividerLocation(0.5);

			leftScrollPane = new JScrollPane();
			fileListSplitPane.setLeftComponent(leftScrollPane);
			leftPanel = new JPanel();
			leftScrollPane.setColumnHeaderView(leftPanel);
			leftPanel.setLayout(null);
			leftPanel.setPreferredSize(new Dimension(100, 222));

			rightScrollPane = new JScrollPane();
			fileListSplitPane.setRightComponent(rightScrollPane);
			rightPanel = new JPanel();
			rightScrollPane.setColumnHeaderView(rightPanel);
			rightPanel.setLayout(null);
			rightPanel.setPreferredSize(new Dimension(100, 222));

			int position = 17;
			JCheckBox[] checkBoxList = new JCheckBox[fileList.size()];
			for (int i = 0; i < fileList.size(); i++) {
				String fileName = fileList.get(i);
				checkBoxList[i] = new JCheckBox(fileName);
			}

			for (int i = 0; i < fileList.size() / 2; i++) {
				JCheckBox checkBox = checkBoxList[i];
				checkBox.setBounds(6, position, 400, 23);
				position += 20;
				leftPanel.add(checkBox);
			}

			position = 17;
			for (int i = fileList.size() / 2; i < fileList.size(); i++) {
				JCheckBox checkBox = checkBoxList[i];
				checkBox.setBounds(6, position, 400, 23);
				position += 20;
				rightPanel.add(checkBox);
			}

			JButton btnDeploy = new JButton("Deploy");
			btnDeploy.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					logger.log(Level.INFO, "Start deployment");
					changeStatus("images\\backup in progress.gif",
							"Deploying...");
					SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
						@Override
						protected Boolean doInBackground() throws Exception {
							deploySelectedFiles(
									Configurations.getExtractedLocation(),
									Configurations.getWebsiteDirectory());
							logger.log(Level.INFO, "Finish deployment");
							return true;
						}

						// Can safely update the GUI from this method.
						protected void done() {
							boolean isIisReset = true;
							changeStatus("images\\backup in progress.gif",
									"Resetting IIS...");
							logger.log(Level.INFO, "Resetting IIS");
							try {
								Process proc = Runtime.getRuntime().exec(
										"iisreset");
								proc.waitFor();
								BufferedReader stdInput = new BufferedReader(
										new InputStreamReader(proc
												.getInputStream()));

								String s = null;
								while ((s = stdInput.readLine()) != null) {
									if (s.contains("Access denied")) {
										isIisReset = false;								
									}
									logger.log(Level.ERROR, s);
								}

							} catch (Exception e) {
								e.printStackTrace();
							}
							logger.log(Level.INFO, "Finished Resetting IIS");
							logger.log(Level.INFO,
									"----------------------------------------");
							final boolean isReset = isIisReset;

							SwingWorker<Boolean, Integer> worker1 = new SwingWorker<Boolean, Integer>() {
								@Override
								protected Boolean doInBackground()
										throws Exception {
									displayDeployComplete(isReset);
									return true;
								}

							};

							worker1.execute();
						}

					};

					worker.execute();
				}
			});
			btnDeploy.setFont(new Font("Tahoma", Font.PLAIN, 14));
			btnDeploy.setBounds(358, 370, 89, 23);
			btnDeploy.setVisible(true);
			fileListPanel.add(btnDeploy);
			fileListPanel.add(fileListSplitPane);
			changeMainWindowContent(fileListPanel);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void deploySelectedFiles(String source, String destination) {
		List<String> selectedFiles = new ArrayList<String>();
		List<Component> checkBoxList = new ArrayList<>(Arrays.asList(leftPanel
				.getComponents()));
		checkBoxList.addAll(Arrays.asList(rightPanel.getComponents()));
		for (int i = 0; i < checkBoxList.size(); i++) {
			JCheckBox checkBox = (JCheckBox) checkBoxList.get(i);
			if (checkBox.isSelected()) {
				selectedFiles.add(checkBox.getText());
			}
		}

		DeployManager deployManager = new DeployManager();
		try {
			deployManager.deploy(source, destination, selectedFiles);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void changeMainWindowContent(JPanel newPanel) {
		mainPanel.setVisible(false);
		if (this.newPanel != null) {
			this.newPanel.setVisible(false);
		}
		this.newPanel = newPanel;
		newPanel.setBounds(0, 0, 814, 547);
		newPanel.setPreferredSize(new Dimension(300, 280));
		newPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		frame.getContentPane().add(newPanel);
		newPanel.setLayout(null);
	}

	public void dispose() {
		frame.setVisible(false);
		frame.dispose();
	}

	public void changeStatus(String imagePath, String text) {
		JPanel newPanel = new JPanel();
		JLabel lblBackUpStatus = new JLabel(text);

		lblBackUpStatus.setIcon(new ImageIcon(imagePath));
		lblBackUpStatus.setBounds(340, 143, 128, 130);
		lblBackUpStatus.setVisible(true);
		newPanel.add(lblBackUpStatus);

		JLabel lblBackingupFiles = new JLabel(text);
		lblBackingupFiles.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblBackingupFiles.setBounds(349, 301, 195, 37);
		newPanel.add(lblBackingupFiles);
		changeMainWindowContent(newPanel);
	}

	public void displayDeployComplete(boolean isIisReset) {
		JPanel newPanel = new JPanel();
		JLabel lblDeployCompleteIcon = new JLabel("Deployment Completed");

		lblDeployCompleteIcon.setIcon(new ImageIcon(
				"images\\Deployment complete.png"));
		lblDeployCompleteIcon.setBounds(340, 110, 128, 130);
		;
		lblDeployCompleteIcon.setVisible(true);
		newPanel.add(lblDeployCompleteIcon);

		JLabel lblDeployComplete = new JLabel("Deployment Completed");
		lblDeployComplete.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblDeployComplete.setBounds(320, 240, 195, 37);
		newPanel.add(lblDeployComplete);

		JButton btnViewLog = new JButton("View Log");
		btnViewLog.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ProcessBuilder pb = new ProcessBuilder("Notepad.exe",
						"logs\\webDeploymentUtility.log");
				try {
					pb.start();
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}
		});
		btnViewLog.setBounds(281, 289, 89, 23);
		btnViewLog.setFont(new Font("Tahoma", Font.PLAIN, 14));
		newPanel.add(btnViewLog);

		JButton btnViewPage = new JButton("Browse Web Page");
		btnViewPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LoadUrlDialog loadUrlDlg = new LoadUrlDialog();
				loadUrlDlg.showLoadUrlWindow();
			}
		});
		btnViewPage.setBounds(381, 289, 160, 23);
		btnViewPage.setFont(new Font("Tahoma", Font.PLAIN, 14));
		newPanel.add(btnViewPage);

		changeMainWindowContent(newPanel);
		if (!isIisReset) {
			JOptionPane
					.showMessageDialog(frame,
							"Could not reset IIS due to permission error. Please reset IIS manually");
		}
	}

	public JFrame getFrame() {
		return frame;
	}
}
